package com.maoye.ossp.sys.base.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.maoye.ossp.common.web.BaseController;
import com.maoye.ossp.sys.base.entity.ContractAttType;
import com.maoye.ossp.sys.base.entity.SysBaseForm;
import com.maoye.ossp.sys.base.entity.SysBaseModule;
import com.maoye.ossp.sys.base.entity.SysDict;
import com.maoye.ossp.sys.base.entity.SysDictDetail;
import com.maoye.ossp.sys.base.service.SysBaseModuleService;
import com.maoye.ossp.sys.site.utils.BeanToMap;
/**
 * 模块controller类
 * @author yangyy2
 * @date   2014-06-06
 */
@Controller
@RequestMapping(value = "sys/base/module/")
public class SysBaseModuleController extends BaseController{
	
	/**
	 * 根节点编号
	 */
	private static final String ROOT = "1";
	/**
	 * 是否存在 (1是 0否)
	 */
	private static final String IS_RESULT_SUCCESS = "0";
	private static final String IS_RESULT_FAIL = "1";
	
	@Resource
	private SysBaseModuleService sysBaseModuleService ;
	
	
	@RequestMapping(value = "list")
	public String list(SysBaseModule sysBaseModule, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		List<SysBaseModule> list = sysBaseModuleService.getList(BeanToMap
				.beanToMap(sysBaseModule));
		model.addAttribute("list", list);
		model.addAttribute("sysBaseModule", sysBaseModule);
		return "/sys/base/module/list";
	}
	
	@RequestMapping(value = "add")
	public String add(SysBaseModule sysBaseModule, Model model) {
		sysBaseModule.setId(0L);
		model.addAttribute("sysBaseModule", sysBaseModule);
		return "/sys/base/module/add";
	}
	
	@RequestMapping(value = "{sysBaseModuleID}/edit")
	public String edit(@PathVariable Long sysBaseModuleID, Model model) {
		SysBaseModule sysBaseModule = sysBaseModuleService.get(sysBaseModuleID);
		model.addAttribute("sysBaseModule", sysBaseModule);
		return "/sys/base/module/add";
	}
	
	@RequestMapping(value = "save", method = RequestMethod.POST)
	public void save(@RequestParam("sysBaseModule")String sysBaseModule,RedirectAttributes redirectAttributes,HttpServletResponse response) throws IOException {
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		Gson gson = new Gson();
		SysBaseModule sysModule = gson.fromJson(sysBaseModule, SysBaseModule.class);
		sysModule.setParentId(ROOT);
		if(sysModule.getId().longValue() == 0l) {
			sysModule.setId(idGenerator.getUId());
			sysModule.setCreateBy("yyy");
			sysBaseModuleService.saveModule(sysModule);
		} else {
			sysModule.setUpdateBy("yyy");
			sysBaseModuleService.updateModule(sysModule);
		}
		
		addMessage(redirectAttributes, "保存数据成功");
		out.write("/sys/base/module/list");
		out.flush();
		out.close();
	}
	
	@RequestMapping(value = "{sysBaseModuleID}/delete")
	public String delete(@PathVariable Long sysBaseModuleID, Model model,
			RedirectAttributes redirectAttributes) {
		sysBaseModuleService.remove(sysBaseModuleID);
		addMessage(redirectAttributes, "删除数据成功！");
		return "redirect:/sys/base/module/list";
	}
	
	/**
	 * 验证模块是否重复
	 * @param id
	 * @param model
	 * @param redirectAttributes
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value = "validate")
	public void validate(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String key = request.getParameter("key");
		String id = request.getParameter("id");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		SysBaseModule sysBaseModule = new SysBaseModule();
		sysBaseModule.setKey(key);
		List<SysBaseModule> list = sysBaseModuleService.getListWithEqual(BeanToMap.beanToMap(sysBaseModule));
		StringBuffer result = new StringBuffer();
		if(list.size() == 1 &&  list.get(0).getId().toString().equals(id)){
			result.append(IS_RESULT_SUCCESS);
		}else if(list.size() > 0){
			result.append(IS_RESULT_FAIL);
		} else {
			result.append(IS_RESULT_SUCCESS);
		}
		out.write(result.toString());
		out.flush();
		out.close();
	}
	
	@RequestMapping(value = "get")
	public void get(ContractAttType contractAttType, HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		StringBuffer json = new StringBuffer();
		Map map = new HashMap();
		ArrayList<SysBaseModule> list= (ArrayList<SysBaseModule>) sysBaseModuleService.getList(map) ;
		json.append("[");
		for (int i = 0; i < list.size(); i++) {
			json.append("{");
			json.append("name:\"").append(list.get(i).getName()).append("\"");                   //name
			json.append(",");
			json.append("id:").append("\"").append(list.get(i).getId()).append("\"");            //id
			json.append(",");
			json.append("pId:").append("\"").append(list.get(i).getParentId()!=null?list.get(i).getParentId():0).append("\"");    //pid
			json.append(",");
			json.append("open:").append("true"); 
			json.append(",");
			json.append("isParent:").append("0".equals(list.get(i).getParentId())?true:false);            //isParent;
			json.append("}");
			json.append(",");
		}
		String outJson=json.substring(0, json.length()-1).toString();
		outJson=outJson+("]");
		System.out.println(outJson);
		out.write(outJson);
		out.flush();
		out.close();
	}


	public static void main(String args[]) {
		String sysBaseModule = "{'id':'0','name':'sss','key':'sss','orderBy':'0','remark':'sss','createBy':'sss'}";
		Gson gson = new Gson();
		SysBaseModule sysModule = gson.fromJson(sysBaseModule, SysBaseModule.class);
		System.out.println(sysModule.toString());
	}
}